import requests 
import xml.etree.ElementTree as ET

HOST = 'https://sso.cuc.edu.cn/cas'
SERVICE = 'http://vlab.cuc.edu.cn'

class CasError(Exception): pass

def logout():
  url = HOST + "/logout"
  PARAMS = {'service': SERVICE + '/login'} 
  r = requests.get(url = url, params = PARAMS)
  # print('logout:{}'.format(r))

def serviceValidate(ticket):
  url = HOST + "/serviceValidate"
  PARAMS = {'service': SERVICE + '/api/cas/login', 'ticket': ticket} 
  try:
    r = requests.get(url = url, params = PARAMS)
    # print(r, r.content, r.status_code)
    root = ET.fromstring(r.content)
    user_id = root[0][0].text
    college_name = root[0][1][2].text
    user_name = root[0][1][4].text
    id_type = root[0][1][6].text
    return user_id, user_name, id_type, college_name
  except:
    raise CasError('INVALID_TICKET')
  